<?php


namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Http\Requests\ApiV2\UserRedpacketRequest;
use App\Http\Requests\ApiV2\RunRequest;
use App\Http\Requests\ApiV2\WeightFragmentRequest;
use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Base\Services\ConfigService;
use App\Services\Business\Models\Run;
use App\Services\Business\Models\UserRedpacketRecord;
use App\Services\Business\Models\WeightFragment;
use App\Services\Business\Interfaces\VideoServiceInterface;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Models\Activity;
use App\Services\Member\Models\UserRechargeBalance;
use App\Services\Member\Models\UserRedpacket;
use App\Services\Member\Services\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use App\Services\Member\Models\UserRedpacketBalance;
use Yansongda\Pay\Pay;


class RunController extends BaseController
{


    /**
     * @var UserService
     */
    protected $userService;


    /**
     * @var ConfigService
     */
    protected $configService;

    protected $businessState;


    public function __construct(

        UserServiceInterface   $userService,
        ConfigServiceInterface $configService,
        BusinessState          $businessState
    )
    {

        $this->userService = $userService;
        $this->businessState = $businessState;
        $this->configService = $configService;

    }


    /**
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request)
    {


        $size = $request->input('size');
        $run = Run::query()
            ->with(['user:id,nick_name,avatar'])
            ->orderBy('created_at', 'desc')->paginate($size);
        return $this->successData(compact('run'));
    }


    public function detail(Request $request, $id)
    {

        $run = Run::query()->with(['user','images','videos','thumbsups'])->where('id', $id)->firstOrFail();
        $isFollowed = false;
        $isThumbsuped = false;
        if ($this->check()) {
            $isFollowed = $this->userService->isFollowed($this->id(), $run->user_id);
            $isThumbsuped = $this->userService->isThumbsuped($this->id(), $id, Run::class);
        }
        return $this->successData(compact('run', 'isFollowed', 'isThumbsuped'));


    }

    /*新增跑步
     * @param RunRequest $request
     * @param Run $run
     * @return JsonResponse
     */
    public function store(RunRequest $request, Run $run)
    {


        $today = Carbon::today();
        $userId = $this->id();
        $data = $request->filldata();
        DB::transaction(function () use ($data, $run, $userId) {
            //处理跑步
            $run->fill($data)->save();
            $run->images()->createMany($data['images']);
            $run->videos()->attach($data['video_ids']);
            $run->activity()->save(new Activity(['user_id' => $userId]));
            $run->load('redpacketRecords', 'redpacketRecords.sender:id,nick_name,avatar');
        });
        //新增的时候排除已经发过红包的人
        $alreadySenderIds = UserRedpacketRecord::query()->where('receiver_id', $userId)->whereDate('created_at', $today)->pluck('sender_id')->toArray();

        $redPackets = UserRedpacket::query()
            ->with(['user:id,nick_name,avatar'])->when($alreadySenderIds, function ($query) use ($alreadySenderIds) {
                $query->whereNotIn('user_id', $alreadySenderIds);
            })
            ->where('receiver_id', $userId)
            ->select(['id', 'receiver_id', 'user_id', 'step', 'reward_value', 'blessing_words'])
            ->where('step', "<", $data['step'])
            ->where('parts', ">", 0)
            ->get()->toArray();
        return $this->successData(compact('run', 'redPackets'));
    }

    public function openRedpacket(Request $request, $runId, $senderId, ConfigServiceInterface $configService)
    {

        $openid = $request->input('openid');
        $money = $request->input('redpacket');
        $blessingWords = $request->input('blessing_words');
        $userId = $this->id();
        $orderId = 't' . time();
        $redpacket = new UserRedpacketRecord([
            'order_id' => $orderId,
            'sender_id' => $senderId,
            'receiver_id' => $userId,
            'blessing_words' => $blessingWords,
            'red_packet' => $money,
            'run_id' => $runId
        ]);
// 使用save方法保存数据
        $redpacket->save();
        $config = $configService->getWechatPay();
        $order = [
            'appid' => 'wx15189f73ac6ca690',
            'out_batch_no' => $orderId,
            'batch_name' => '活动奖励',
            'batch_remark' => $blessingWords,
            'total_amount' => round($money * 100),
            'total_num' => 1,
            'notify_url' => route('payment.callback', ['wechat-mini']),
            'transfer_detail_list' => [
                [
                    'out_detail_no' => 'd' . time(),
                    'transfer_amount' => round($money * 100),
                    'transfer_remark' => $blessingWords,
                    'openid' => $openid,

                ],
            ],
        ];
        $result = Pay::wechat($config)->transfer(
            $order
        );

        return $this->successData(compact('redpacket'));

    }

    /**跑步的编辑
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function edit(Request $request, $id)
    {

        $run = Run::query()
            ->where('id', $id)
            ->firstOrFail();
        return $this->successData(compact("run"));

    }


    function delete($id, ConfigServiceInterface $configService, VideoServiceInterface $videoService)
    {
        $run = Run::query()->where('id', $id)->first();

        DB::transaction(function () use ($run, $videoService, $configService) {

            //删除视频点播的图片
            if ($run->images->isNotEmpty()) {
                $run->images()->delete();
                $images = $run->images->flatMap(function ($image) {
                    return [$image->url, $image->small_url];
                })->toArray();
                Storage::disk('oss')->delete($images);
            }

            //删除阿里云的视频
            if ($run->videos->isNotEmpty()) {
                $run->videos()->detach();
                $run->videos()->delete();
                $videoService->deleteVideo(implode(',', $run->videos->pluck('aliyun_video_id')->toArray()), $configService);
            }
            //删除跑步本身

            $run->delete();
            //删除动态本身
            $run->activity()->delete();


        });

        return $this->success(__('删除成功'));
    }


    function update(WeightFragmentRequest $request, $id)
    {

        $data = $request->filldata();
        $fragment = Run::query()->where('id', $id)->first();
        DB::transaction(function () use ($fragment, $data) {

            $fragment->fill($data)->save($data);
            $fragment->images()->delete();
            $fragment->images()->createMany($data['images']);
            $fragment->videos()->sync($data['video_ids']);

        });
        return $this->success(__('更新成功'));
    }

    /**新增收红包的人
     * @param UserRedpacketRequest $request
     * @param UserRedpacket $redpacket
     * @return JsonResponse
     */
    public function updateRedpacket(UserRedpacketRequest $request, $id)
    {
        $data = $request->filldata();
        $redpacket = UserRedpacket::query()->where('id', $id)->first();
        $user = Auth::user();
        if ($data['total']  > $user['account'] + $redpacket['total']) {
            return $this->error(__('余额不够'));
        }

        DB::transaction(function () use ($data, $id, $redpacket, $user) {

                //添加红包记录
                UserRedpacketBalance::create(['receiver_id' => $data['receiver_id'], 'user_id' => $user['id'], 'title' => $data['total'] > $redpacket['total'] ? "充值红包" : "减少红包", 'balance' => $data['total'] - $redpacket['total'], 'remain' => $data['total']]);
                //添加账户余额记录
                UserRechargeBalance::create(['user_id'=>$user['id'],'title' => $data['total'] > $redpacket['total'] ? "充值红包" : "减少红包", "balance" => $data['total'] - $redpacket['total'], 'remain' => $user['account'] - ($data['total'] - $redpacket['total'])]);
                //更改账户记录
                $user->update(['account' => $user['account'] - ($data['total'] - $redpacket['total'])]);


            $redpacket->fill($data)->save();
        });
        return $this->success(__('更新成功'));


    }

    /**
     *送祝福
     * @param UserRedpacketRequest $request
     * @param UserRedpacket $redpacket
     * @return JsonResponse
     */
    public function storeRedpacket(UserRedpacketRequest $request, UserRedpacket $redpacket)
    {


        $data = $request->filldata();
        if (UserRedpacket::query()->where('user_id', $this->id())->where('receiver_id', $data['receiver_id'])->exists()) {
            return $this->error(__('不能重复添加'));
        }
        $user = Auth::user();
        if ($data['total'] > $user['account']) {
            return $this->error(__('余额不够'));
        }
        DB::transaction(function () use ($data, $redpacket, $user) {
            //添加红包记录
            UserRedpacketBalance::create(['receiver_id' => $data['receiver_id'], 'user_id' => $user['id'], 'title' => "充值红包", 'balance' => $data['total'], 'remain' => $data['total']]);
            //添加账户余额记录
            UserRechargeBalance::create(['user_id' => $user['id'], 'title' => "充值红包", "balance" => $data['total'], 'remain' => $user['account'] - $data['total']]);
            //更改账户记录
            $user->update(['account' => $user['account'] - $data['total']]);
            $redpacket->fill($data)->save();
        });
        return $this->success(__('新增成功'));


    }

    /**
     * 删除祝福的人
     * @param UserRedpacket $redpacket
     * @param $id
     * @return JsonResponse
     */
    public function deleteRedpacket(UserRedpacket $redpacket, $id)
    {


        $user = Auth::user();
        $redpacket = UserRedpacket::query()->where('id', $id)->first();
        DB::transaction(function () use ($redpacket, $user, $id) {

            // 删除记录
            $redpacket->delete();
            //添加红包记录
            UserRedpacketBalance::create(['receiver_id' => $redpacket['receiver_id'], 'user_id' => $user['id'], 'title' => "退还红包", 'balance' => $redpacket['total'], 'remain' => 0]);
            //添加账户余额记录
            UserRechargeBalance::create(['user_id' => $user['id'], 'title' => "退还红包", "balance" => $redpacket['total'], 'remain' => $user['account'] + $redpacket['total']]);
            //更改账户记录
            $user->update(['account' => $user['account'] + $redpacket['total']]);


        });
        return $this->success(__('删除成功'));


    }


    public function editRedpacket($id)
    {
        $redpacket = UserRedpacket::query()->with(['receiver'])->where('id', $id)->first();
        return $this->successData(compact('redpacket'));


    }

    /**
     * 答谢红包留言
     * @param Request $request
     * @param $id
     * @return JsonResponse
     */
    public function redpacketReply(Request $request, $id)
    {
        $words = $request->input('words');
        $record = UserRedpacketRecord::query()->where('id', $id)->first();
        $record->update(['reply_words' => $words]);
        return $this->success(__('successful'));


    }

}
